package com.vegetable.modules.service.sys.impl;

import com.vegetable.modules.entity.sys.SysUserEntity;
import com.vegetable.modules.service.sys.OnlineUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 在线用户服务实现类
 */
@Slf4j
@Service("onlineUserService")
public class OnlineUserServiceImpl implements OnlineUserService {

    /**
     * 在线用户集合，key为用户ID，value为用户信息
     */
    private final Map<Long, OnlineUser> onlineUsers = new ConcurrentHashMap<>();

    /**
     * Token与用户ID的映射，key为token，value为用户ID
     */
    private final Map<String, Long> tokenToUser = new ConcurrentHashMap<>();

    /**
     * 用户ID与Token的映射，key为用户ID，value为token
     */
    private final Map<Long, String> userToToken = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        log.info("OnlineUserService initialized");
    }

    @PreDestroy
    public void destroy() {
        log.info("OnlineUserService destroyed, clearing online users");
        onlineUsers.clear();
        tokenToUser.clear();
        userToToken.clear();
    }

    @Override
    public void addUser(SysUserEntity user, String token) {
        if (user == null || token == null || user.getUserId() == null) {
            return;
        }

        // 如果用户已经在线，先移除旧记录
        removeUser(user.getUserId());

        // 添加新记录
        onlineUsers.put(user.getUserId(), new OnlineUser(user, System.currentTimeMillis()));
        tokenToUser.put(token, user.getUserId());
        userToToken.put(user.getUserId(), token);

        log.info("User {} added to online users", user.getUsername());
    }

    @Override
    public void removeUser(Long userId) {
        if (userId == null) {
            return;
        }

        OnlineUser removedUser = onlineUsers.remove(userId);
        if (removedUser != null) {
            String token = userToToken.remove(userId);
            if (token != null) {
                tokenToUser.remove(token);
            }
            log.info("User {} removed from online users", removedUser.getUser().getUsername());
        }
    }

    @Override
    public List<SysUserEntity> getOnlineUsers() {
        List<SysUserEntity> users = new ArrayList<>();
        for (OnlineUser onlineUser : onlineUsers.values()) {
            // 返回用户副本，隐藏敏感信息
            SysUserEntity user = copyUser(onlineUser.getUser());
            users.add(user);
        }
        return users;
    }

    @Override
    public boolean isUserOnline(Long userId) {
        return userId != null && onlineUsers.containsKey(userId);
    }

    @Override
    public Long getUserIdByToken(String token) {
        return token != null ? tokenToUser.get(token) : null;
    }

    /**
     * 复制用户信息，隐藏敏感字段
     * @param original 原始用户对象
     * @return 用户副本
     */
    private SysUserEntity copyUser(SysUserEntity original) {
        SysUserEntity copy = new SysUserEntity();
        copy.setUserId(original.getUserId());
        copy.setUsername(original.getUsername());
        copy.setRealName(original.getRealName());
        copy.setEmail(original.getEmail());
        copy.setMobile(original.getMobile());
        copy.setStatus(original.getStatus());
        copy.setCreateTime(original.getCreateTime());
        // 不复制密码、盐值等敏感信息
        return copy;
    }

    /**
     * 在线用户内部类，包含用户信息和登录时间
     */
    private static class OnlineUser {
        private final SysUserEntity user;
        private final long loginTime;

        public OnlineUser(SysUserEntity user, long loginTime) {
            this.user = user;
            this.loginTime = loginTime;
        }

        public SysUserEntity getUser() {
            return user;
        }

        public long getLoginTime() {
            return loginTime;
        }
    }
}